<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;

class Login extends Controller
{
    /**
     * 后台登录页面加载
     * @return [type] [description]
     */
    public function index()
    {
        return $this->fetch('login',['title'=>'蒸汽男孩后台登录']);
    }

    /**
     * 执行登录逻辑
     * @param  Request $req [description]
     * @return [type]       [description]
     */
    public function dologin(Request $req)
    {
        // 获取post信息
        $admin = $req->post();

        // 查询数据库账号信息匹配
        $data = Db::name('admin')->where('name = "'.$admin['name'].'" and pass = "'.md5($admin['pass']).'"')->find();

        if(!empty($data)){

            // 成功生成session
            Session::set('admin',$data['name']);
            Session::set('admin_id',$data['id']);

            $id = Session::get('admin_id');


            // 查询登录用户的所有节点
            $list = Db::view('node','mname,aname')
            ->view('role_node','nid','node.id = role_node.nid')
            ->view('admin_role','rid','role_node.rid = admin_role.rid')
            ->view('admin','id','admin.id = admin_role.aid')
            ->where('id','=',$id)->select();

            // 控制器名转换大写
            foreach ($list as $key => $val) {
                $list[$key]['mname'] = ucfirst($val['mname']);
            }

            $nodelist = array();

            //遍历重新拼装
            foreach($list as $v){
                $nodelist[$v['mname']][] = $v['aname'];
            }

            // 设置获得的控制器和方法 存入session
            Session::set('qx',$nodelist);

            // 跳转后台首页
            $this->success('登录成功!',url('admin/index/index'));
        }else{
            // 失败返回登录页面
            $this->error('登录失败!',url('admin/login/index'));
        }
    }

    /**
     * 执行退出逻辑
     * @return [type] [description]
     */
    public function outlogin()
    {
        // 清除所有session
        Session::delete('admin');
        Session::delete('admin_id');
        Session::delete('qx');
        $this->success('退出成功',url('admin/login/index'));
    }
}
